package no.uio.ifi.cop.cl;

import java.util.Set;
import no.uio.ifi.cop.common.Log;
import no.uio.ifi.cop.parse.formula.TermFactory;

/**
 * Holds variables inside Terms (Predicates).
 *
 * Note that variables are not identical in
 * terms of pointers so comparison of pointers
 * like those of Constants will not work.
 *
 *
 * @version 1.0
 * @author  bjarneh@ifi.uio.no
 */

public final class Variable implements Term, Cloneable{

    private String id;

    public Variable(String id){
        this.id = id;
    }

    public boolean match(Substitution subst, Term other){
        if( other.isVariable() ){
            Log.fatal("matching open terms => %s + %s", this, other);
        }
        return subst.add( this, other );
    }

    public Substitution smatch(Term other){
        return null;
    }

    public String getId()  { return id;    }
    public String strType(){ return "Variable"; }

    public boolean isVariable() { return true;  }
    public boolean isPredicate(){ return false; }
    public boolean isConstant() { return false; }

    public void gatherVariables(Set<String> set){
        set.add(id);
    }

    public Term apply(Substitution subst){ return this; }
    public String toString(){ return id;  }
    public int hashCode(){ return id.hashCode(); }

    // this kind of ugly casting is caused by the fact
    // that HashMaps only calls the equals(Object) method.
    public boolean equals(Object other){
        if( other instanceof Variable ){
            Variable v_other = (Variable) other;
            return v_other.getId().equals(id);
        }
        return false;
    }

    public Variable clone(){
        return TermFactory.getVariableCopy( id );
    }
}
